package com.z.redis.command.impl;

import com.z.redis.RedisCore;
import com.z.redis.command.Command;
import com.z.redis.command.CommandType;
import com.z.redis.resp.BulkString;
import com.z.redis.resp.Resp;
import com.z.redis.resp.SimpleString;
import io.netty.channel.ChannelHandlerContext;

/**
 * 检测连通性
 */
public class Ping implements Command {
    private String message; // 有参数的话记录参数
    private boolean flag = true; // 检测输入的参数是否合法

    @Override
    public CommandType type(){
        return CommandType.ping;
    }

    @Override
    public void setContent(Resp[] array){
        if (array.length == 2) {
            message = ((BulkString)array[1]).getContent().toUTF8String();
            System.out.println(message);
        } else if(array.length > 2){
            flag = false;
        }
    }

    @Override
    public void handle(ChannelHandlerContext ctx, RedisCore redisCore){
        if(flag == false){
            ctx.write(new SimpleString("Unsupported command"));
        } else{
            if(message == null){
                ctx.write(new SimpleString("PONG"));  // 响应
            } else{
                ctx.write(new SimpleString(message));
            }
        }
        ctx.flush();
    }
}
